<?php

if_get('/tags', function ()
{/*{{{*/
    list(
        $inputs['group_id']
    ) = input_list(
        'group_id'
    );

    $inputs = array_filter($inputs, 'not_null');

    $tags = dao('tag')->find_all_by_column($inputs);

    return array_build($tags, function ($id, $tag) {
        return [
            null,
            [
                'id' => $tag->id,
                'name' => $tag->name,
                'group_id' => $tag->group->id,
                'group_display' => $tag->group->display_for_tags_group(),
                'create_time' => $tag->create_time,
                'update_time' => $tag->update_time,
            ]
        ];
    });
});/*}}}*/

if_post('/tags/add', function ()
{/*{{{*/
    $name = input('name');
    otherwise_error_code(40001, $name);

    $extends_info = input('extends_info', '');

    $tag = tag::create($name);

    $tag->extends_info = $extends_info;

    if ($group_id = input('group_id')) {
        $group = dao('group')->find($group_id);
        otherwise_error_code(20002, $group->is_not_null());

        $tag->group = $group;
    }

    return [
        'id' => $tag->id,
    ];
});/*}}}*/

if_post('/tags/update/*', function ($tag_id)
{/*{{{*/
    $name = input('name');
    otherwise_error_code(40001, $name);

    $tag = dao('tag')->find($tag_id);
    otherwise($tag->is_not_null(), 'tag 不存在');

    if ($group_id = input('group_id')) {
        $group = dao('group')->find($group_id);
        otherwise_error_code(20002, $group->is_not_null());

        $tag->group = $group;
    }

    $tag->name = $name;

    $extends_info = input('extends_info', null);
    if (not_null($extends_info)) {
        $tag->extends_info = $extends_info;
    }

    return true;
});/*}}}*/

if_post('/tags/delete/*', function ($tag_id)
{/*{{{*/
    $tag = dao('tag')->find($tag_id);
    otherwise($tag->is_not_null(), 'tag 不存在');

    $tag->delete();

    return true;
});/*}}}*/
